//
//  CLRefreshControl.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/15.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
//控件的高度
private let CLRefreshControlHeight:CGFloat = 50
//下拉刷新的枚举类型
enum CLRefreshControlType:Int {
    //下拉刷新
    case Normal = 0
    //释放刷新
    case Pulling = 1
    //正在加载
    case Refreshing = 2
}
class CLRefreshControl: UIControl {

  //默认当前下拉刷新的状态
    private var refreshStatu:CLRefreshControlType = .Normal {
        didSet {
            switch refreshStatu {
            case .Normal:
                print("下拉刷新")
                //设置内容  箭头重置
                messageLabel.text = "下拉刷新"
                //显示图片
                iconImageView.hidden = false
                //关闭风火轮 停止动画就表示关闭了
                activityIndicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //重置动画   还原之前样式
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                //oldValue是上一次的储存值
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= CLRefreshControlHeight
                    })
                }
            case .Pulling:
                print("释放刷新")
                //释放刷新,箭头调转
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat( M_PI))
                })
            case .Refreshing:
                print("正在刷新")
                messageLabel.text = "正在刷新"
                iconImageView.hidden = true
                //开启风火轮
                activityIndicatorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += CLRefreshControlHeight
                })
                //通知外界用于加载数据 请求方法
                sendActionsForControlEvents(.ValueChanged)
            }
            
        }
    }
    
    //当前滚动的视图
    var currentScrollView:UIScrollView?
    // MARK:  懒加载控件
    //箭头
    private lazy var iconImageView:UIImageView = UIImageView(image:UIImage(named: "tableview_pull_refresh"))
    //刷新文本
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.grayColor()
        label.text = "下拉刷新"
        return label
    }()
    //风火轮
    private lazy var  activityIndicatorView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        return view
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUpUI() {
        backgroundColor = UIColor.whiteColor()
        //添加控件
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(activityIndicatorView)
        //设置约束 使用系统方法来布局
        //箭头图片
        iconImageView.translatesAutoresizingMaskIntoConstraints = false //关掉自动约束
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute:NSLayoutAttribute.CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        //文字信息
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        //风火轮
        activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: activityIndicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: activityIndicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
    }
    //将要添加到哪个父控件的时候去调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断其父控件是否能滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: CLRefreshControlHeight)
        self.frame.origin.y = -CLRefreshControlHeight
        //使用kvo监听其父控件的滚动
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrollView = scrollView
    }
    //kvo的监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//       0 print(currentScrollView?.contentOffset.y)
        guard let scrollView = currentScrollView else {
            return
        }
        /*
        1.如果拖动情况下,有两种状态 1，下拉刷新 2，释放刷新
        2.如果松手情况下,就要进入"正在刷新状态"前提（当前的刷新状态 松手就刷新的状态）
        */
        
        if scrollView.dragging {
            if scrollView.contentOffset.y < -(scrollView.contentInset.top + CLRefreshControlHeight) && refreshStatu == .Normal {
                print("松手刷新")
                refreshStatu = .Pulling
            } else if scrollView.contentOffset.y >= -(scrollView.contentInset.top + CLRefreshControlHeight) && refreshStatu == .Pulling {
                print("下拉刷新")
                refreshStatu = .Normal
            }
        }else {
            if refreshStatu == .Pulling {
                refreshStatu = .Refreshing
                print( "正在刷新")
            }
        }
        
        
        
        
    }
    //结束刷新
    func endRefreshing() {
        //将状态调为原始状态
        refreshStatu = .Normal
    }
    //移除kvo
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
